I have a node js app acting as a middle layer for an ai project I'm working on.
I want to re-route a request (given logic to determine if the request need to be re-routed, and other things). This will be an POST api call (aka no redirects allowed).
Instead of setting up a proxy middleware, i see the request can be piped using the request lib.
However, it seems the post request gets a write error, if i say to close the original POST request stream, it errors saying i cant write to a closed stream. Error: write after end
req.pipe(request({
url: `${AI_BRAIN_URL}/project/${ai_project_key}`,
method: 'POST',
headers: req.headers,
body: JSON.stringify(req.body)
})).pipe(res)
So, i tell the post request stream to remain open, and to close it in the next pipe .pipe(res, {end:true}.
I figure since pipe merges the streams, the resulting stream should be closed.
Is my assumption correct? How can i tell all the streams are closing?
Final code
async function routeToBrain(req, res, next) {
const { ai_project_key } = req.body
const { user_key } = req.user
// logic to determine routing
return req.pipe(request({
url: `${AI_BRAIN_URL}/project/${ai_project_key}`,
method: 'POST',
headers: req.headers,
body: JSON.stringify(req.body)
}), { end: false }).pipe(res, { end: true })
}